package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.common.constants.JwtConstants.*;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    //feign远程调用user微服务
    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    //用户登录功能
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        //1.根据用户名和密码查询用户
        UserDTO userDTO = null;
        try {
            userDTO = userClient.queryUserByNameAndPassword(username, password);
        } catch (FeignException e) {
            //feign 调用 queryUserByNameAndPassword() 这个方法可能会产生的异常
            if (e.status() == 400){
                //用户名或密码错误
                throw new LyException(e.status(),e.contentUTF8());
            }
            //其他异常
            throw new LyException(500,"验证用户失败！",e);
        }
        //2.对查询结果做判断
        if (userDTO == null){
            //用户不存在
            throw new LyException(401,"用户名或密码错误");
        }
        //3.生成JWT
        String jwt = jwtUtils.createJwt(UserDetails.of(userDTO.getId(), userDTO.getUsername()));
        //4.写入cookie
        writeJwtCookie(response,jwt);
    }

    //退出登录
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if (jwt == null){
            //用户并未登录
            return;
        }
        try {
            // 2.解析jwt
            Payload payload = jwtUtils.parseJwt(jwt);
            // 3.删除redis
            Long userId = payload.getUserDetail().getId();
            jwtUtils.deleteJwt(userId);
        } catch (Exception e) {
            // 解析jwt失败，有可能是未登录，放弃退出
        }
        // 4.删除cookie
        CookieUtils.deleteCookie(COOKIE_NAME,DOMAIN,response);
    }

    private void writeJwtCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME,jwt);
        // cookie作用的路径，/代表一切路径
        cookie.setPath(COOKIE_PATH);
        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);
        // cookie的作用域
        cookie.setDomain(DOMAIN);
        // 默认  cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        //cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }
}
